package com.example.nio.controller;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.system.UserInfo;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.example.nio.commons.Message;
import com.example.nio.entity.AppConfig;
import com.example.nio.entity.WxIndividualMessage;
import com.example.nio.entity.WxUserInfo;
import com.example.nio.service.MessageSendService;
import com.example.nio.service.WxUserService;
import com.example.nio.util.DataTransUtil;
import com.example.nio.util.WxUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;



@Controller
public class WXController   {
    // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0fee784a2fc6a75&redirect_uri=https://53564tm804.uicp.fun/getUserInfoByCode&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect
    private final String getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=@{appId}&redirect_uri=@{redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
    private final String getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=@{appId}&secret=@{secret}&code=@{code}&grant_type=authorization_code";
    private final String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=@{accessToken}&openid=@{openId}&lang=zh_CN";

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/jxth")
    @ResponseBody
    public String token(HttpServletRequest request){
        // 微信公众号会发送过来 确认认证是否正确
        String echoStr =  request.getParameter("echostr");
        return echoStr;
    }
    // 业务域名开放验证地址
    @RequestMapping("MP_verify_2F6tdhplFiueD8UJ.txt")
    @ResponseBody
    public String wxCheck(){
        //直接返回你下载的授权文件里的内容就好
        return "2F6tdhplFiueD8UJ";
    }

    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private WxUtils wxUtils;
    @Autowired
    private MessageSendService messageSendService;

    private LinkedList onlineUser = new LinkedList<>();

    // 接受微信推送的消息 method POST
    @PostMapping("/jxth")
    @ResponseBody
    public void jxth(HttpServletRequest request) {
        DataTransUtil transUtil = new DataTransUtil();
        String toJSONObject = transUtil.xmlToJSONObject(request);
        System.out.println(toJSONObject);
        JSONObject jsonObject = (JSONObject) JSONUtil.parseObj(toJSONObject).get("xml");
        System.out.println(jsonObject);
        // 从微信发送过来的消息
        if ("CLICK".equals(jsonObject.get("Event"))&& ("rengong").equals(jsonObject.get("EventKey"))){
            jsonObject.put("Content","接入客服");
            onlineUser.add(jsonObject.get("FromUserName"));
            // 通过openid获取wxUser对象 如果没有昵称就发送一个授权链接给用户
            WxUserInfo wxUser = wxUserService.query().eq("openid", jsonObject.get("FromUserName")).one();
            if (wxUser == null){
                wxUser = new WxUserInfo();
                wxUser.setOpenid((String) jsonObject.get("FromUserName"));
                wxUserService.save(wxUser);
            }
            //
            if (wxUser.getNickname()==null){
                Message message = new Message();
                message.setFromUser(jsonObject.get("ToUserName").toString());
                message.setToUser(jsonObject.get("FromUserName").toString());
                message.setContent("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0fee784a2fc6a75&redirect_uri=https://53564tm804.uicp.fun/getUserInfoByCode&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect");
                System.out.println("发送授权页面给用户");
                wxUtils.sendToWx(message);
            }
        }
        if (onlineUser.stream().anyMatch(item -> jsonObject.get("FromUserName").equals(item))){
            /**
             * {
             *     "xml":{
             *         "MediaId":"EcgaAG23BxQqynvy1TVMpcTmvKTLXTPdtwdrD8oVUYnZtS9g5Ko8rjknxyvtDvF3",
             *         "CreateTime":1657183892,
             *         "ToUserName":"gh_57db6cbb50af",
             *         "FromUserName":"oGS2a6QJTWICqnQoUWiTNFyqkHUk",
             *         "MsgType":"image",
             *         "PicUrl":"http://mmbiz.qpic.cn/mmbiz_jpg/aIoI8PDE46WaUYWHQfaXWUI3MHZ8CicTnlWVxzkZeDnOU2giaKR1W7F6aeJaDDC52TLrtpZQSGibibs8UpCG02I0yw/0",
             *         "MsgId":23725169851174965,
             *         "Encrypt":"Cmllfq6Qy4gG0TLvIP0Jrz1yJfZnYWkDbHn7nfy6XYAw8aJ2/0zxeja+IzeNl/PxfCIVNcrI7e3B4np+YvjeeO6uXER9CMXjB3wMM+TTchnCx6tane49opGr6U/VmR/1a2DUTGgkyh+F3hVOB2rEAAgBqJtO4KdH2g+VDNuhB1MKoyGRwAdV9gI9Z5qUnYM7/VUEgjOZprZcUvNGmblYH8vz2lmY1I5KVKJYSJSyj8w8Cdt+Ys/o0WDSRg+/mrh5saE2Fd0eB6gToc1Xwk6PJgZ3J+n1sqK6zn1uaLGL5i5uVMx/24VTkFxwNG9l4q4PGXSvVVt+wO0cgUZD3N8Yb7uUPzf74MdUwGoa8dAE+NzgCsI4N6oLnS7orCgU+lOEVmlntL+l+TM/EvD+Y7UQv0HEVUCfMu2GGaZkPJTIUl9piCx3/90FWLu70EY9mKpq8/n6jqVA+EPaBJ4vMZqXYVFxk2ZuZCCN8KbAAECFeXGzkjW2ywy+GOBEGDTcY2SozgXzflCFEH+xPuHmBbgcvb9vBCcS0uox0Cdyk09OouXpwqWLJNa6jL/ljz00QIUb3ue8VCLjT/pdLxHSQiP+5q7BVR1PFhtHXV9UnEmk2iIdJ5qsP44l0PHcAs5M0slUqlQZ35Vk7qKp5Q/QYLuUP2yZyiAMubw6AGiX3OhF6dpaWdf4QLoCcVQ/WIj7tzxFaT1RKvDI+yvIqJ9C/ctNGw=="
             *     }
             * }
             *
             *{
             *     "xml":{
             *         "Content":"23",
             *         "CreateTime":1657183902,
             *         "ToUserName":"gh_57db6cbb50af",
             *         "FromUserName":"oGS2a6QJTWICqnQoUWiTNFyqkHUk",
             *         "MsgType":"text",
             *         "MsgId":23725171213263215,
             *         "Encrypt":"Pz5DlMjqhLLPpbuPfC2ujrdyqWq6WtKcXoD2RjbghJlAP9DBS7I2HHJRunmGqRvb+B0zRGBB/wtiACO+Q1pGZ/W6N0VI75dU4ixXeIL5U80fYlRGjxJ8y6669F5GMcIxMF2aHM+1QAPWbsM8SvJFcy1IFpjtlIbJGxw2bMbCGSnT52uvhaskVpOgUWJVDIqG/8Q+tb+fQMr4pEvSU5C13F6EaMnw+iVOzFuTEmLCmEYP/ogPZGGLW1km4UkgQCFf+U57RsY2oA+9giuOGgvLV1IASe4+EM7qHjPygov2GpTwzvql6PbN5Kc0+clOJDXNuG0dX0TlmIfskz6z4XrwJ5rwVyT7gBMletsk9v/9IsUo15FhJs8qe1H3LxAAW8i4ZGPOwWC0CG93h2tEq7FkVB3CPBJjrZ5XGA8a/3KSJqQ="
             *     }
             * }
             */
            Message message = new Message();
            message.setMsgType(jsonObject.get("MsgType").toString());
            if("text".equals(jsonObject.get("MsgType"))){
                message.setContent(jsonObject.get("Content").toString());
            } else if ("image".equals(jsonObject.get("MsgType"))){
                message.setMsgType("img");
                String localFileUrl = wxUtils.doImgUpload(jsonObject.get("PicUrl").toString(), jsonObject.get("MsgId").toString());
                message.setContent(localFileUrl);
            }
            System.out.println("发送消息给客服：" + jsonObject.get("Content"));
            message.setFromUser(jsonObject.get("FromUserName").toString());
            message.setToUser(jsonObject.get("ToUserName").toString());
            message.setMessageSource(2);
            message.setCreateTime(jsonObject.get("CreateTime").toString());
            message.setSystemTime(System.currentTimeMillis());
            messageSendService.messageHandling(message);
        }


//        Iterator<Map.Entry<String, Object>> iterator = jsonObject.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<String, Object> entry = iterator.next();
//            System.out.println("key = " +entry.getKey() + ",value = " + String.valueOf(entry.getValue()));
//        }
    }

    // 通过微信网页授权获取头像
    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0fee784a2fc6a75&redirect_uri=http://f66haq.natappfree.cc/hi&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect
    @RequestMapping(value="/getUserInfoByCode")
    public String sayHello(HttpServletRequest request, @RequestParam("code")String code, @RequestParam("state")String state){
        try {
            if ("neirong".equals(state)){
                getByHttpClient(code);
            }
        } catch (IOException e) {
            System.out.println("请求失败：" + e.getMessage());
        }
        getBYRestTemplate(code);
        System.out.println(code);
        return  "index";
//        showImg(response,(String) map1.get("headimgurl"));
    }
    // 使用restTemplate获取微信头像和昵称
    public void getBYRestTemplate(String code){
        // 获取accessToken
        String baseUrl = getAccessTokenUrl.replace("@{secret}", AppConfig.secret);
        baseUrl = baseUrl.replace("@{appId}", AppConfig.appId);
        baseUrl = baseUrl.replace("@{code}", code);

        String tokenResponse = restTemplate.getForObject(baseUrl, String.class);
        JSONObject map =  JSONUtil.parseObj(tokenResponse);
        String openid = (String) map.get("openid");
        String accessToken = (String) map.get("access_token");
        // 获取用户信息
        String url = getUserInfo.replace("@{accessToken}",accessToken);
        url = url.replace("@{openId}",openid);
        String userInfoResponse = restTemplate.getForObject(url, String.class);
        System.out.println(userInfoResponse);
        WxIndividualMessage wxIndividualMessage =  JSONUtil.toBean(userInfoResponse, WxIndividualMessage.class);
        System.out.println(wxIndividualMessage.toString());
        WxUserInfo userInfo = Convert.convert(WxUserInfo.class,wxIndividualMessage);
        userInfo.setHeadimg(wxIndividualMessage.getHeadimgurl());
        boolean save = wxUserService.updateById(userInfo);
        System.out.println("成功保存用户信息" + save);
    }
    // httpclient请求 获取头像和昵称
    public void getByHttpClient(String code) throws IOException {
        String appId = "wxf0fee784a2fc6a75";
        String secret = "d58ec09a0f63f14d07025be447f9c8b4";
        WxIndividualMessage aim = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 拼接URL
        String url = getAccessTokenUrl.replace("@{appId}", appId).replace("@{secret}", secret).replace("@{code}", code);

        HttpGet get = new HttpGet(url);
        // 设置表头
//        get.setHeader("Content-type", "application/json;charset=utf-8");
//        get.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        // 获取结果实体
        HttpEntity entity = httpClient.execute(get).getEntity();
        JSONObject accessTokenObject = null;
        if (entity != null) {
            // 按指定编码转换结果实体为String类型
            String json = EntityUtils.toString(entity, "UTF-8");
//            logger.info(json);
            accessTokenObject = JSONUtil.parseObj(json);
        }

        String openid = (String) accessTokenObject.get("openid");
        String accessToken = (String) accessTokenObject.get("access_token");
        // 获取用户信息
        String getUserInfoUrl = getUserInfo.replace("@{accessToken}",accessToken).replace("@{openId}",openid);
        HttpGet get1 = new HttpGet(getUserInfoUrl);
        HttpEntity UserInfo = httpClient.execute(get1).getEntity();

        if (UserInfo != null) {
            // 按指定编码转换结果实体为String类型
            String json = EntityUtils.toString(UserInfo, "UTF-8");
//            logger.info(json);
            aim = JSONUtil.toBean(json, WxIndividualMessage.class);
        }
        EntityUtils.consume(entity);
        EntityUtils.consume(UserInfo);
        System.out.println(aim.toString());

    }
    // 读取微信图片并返回
    public void showImg(HttpServletResponse response, String fileUrl) {
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
                FileCopyUtils.copy(connection.getInputStream(),response.getOutputStream());
                response.setContentType("application/octet-stream");
            }
        }catch (IOException e){
            System.out.println("获取头像失败");
        }

    }
}
